#include <lnxTime.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <threadExcuter.h>

static struct lnxTime tmNow;
static uint64_t tmbeginMs = 0;
// linux time thread
static struct thrdExeStct lnxTmTrd;

void upTmFromSys()
{
    struct timeval tmptm;
    thrdExeLock(&lnxTmTrd);
    tmbeginMs = systemNowMs();
    gettimeofday(&tmptm, NULL);
    tmNow.stampMs = tmptm.tv_sec * 1000;
    thrdExeUnlock(&lnxTmTrd);
}

void upTmToSys(uint64_t stampSec)
{
    struct timeval tmptm;
    struct tmdate tmpdate = stamp2date(stampSec, 0);
    logdebug("%d-%d-%d %d:%d:%d", tmpdate.year, tmpdate.month, tmpdate.day, tmpdate.hour, tmpdate.minute, tmpdate.second);
    tmptm.tv_sec = stampSec;
    tmptm.tv_usec = 0;
    settimeofday(&tmptm, NULL);
    system("hwclock -w -f /dev/rtc1");
    upTmFromSys();
}

void *lnxTmRun(void *ptr)
{
    struct thrdExeStct *tmpThrd = (struct thrdExeStct *)ptr;
    upTmFromSys();
    while (tmpThrd->threadRunflag)
    {
        usleep(1000);
        tmNow.stampMs += systemNowMs() - tmbeginMs;
        tmNow.date = stamp2date(tmNow.stampMs / 1000, 0);
    }
    return NULL;
}

struct lnxTime lnxGetTime()
{
    return tmNow;
}

void lnxTmBegin()
{
    thrdExeInit(&lnxTmTrd, lnxTmRun, NULL);
    thrdExeBegin(&lnxTmTrd);
}

void lnxTmQuit()
{
    thrdExeQuit(&lnxTmTrd);
}
